<?php


class WSB_View_Helper_FormSelectCsv extends Zend_View_Helper_FormSelect
{

	/**
	 * @param string $name
	 * @param mixed $value
	 * @param array $attribs
	 * @param array $options
	 * @param string $listsep
	 * @return string
	 */
	public function formSelectCsv($name, $value = null, $attribs = null,
        $options = null, $listsep = "<br />\n") {

        $info = $this->_getInfo($name, $value, $attribs, $options, $listsep);
        extract($info); // name, id, value, attribs, options, listsep, disable

      	// Helper Definitionen
      	$helperName		= $this->_buildHelperName($name);
      	$helperValue	= $this->_csvToArray($value);
      	$helperAttribs	= $attribs;
      	$helperAttribs['onchange'] = $this->_buildJsOnChange($name);
      	$helperOptions	= $options; //$this->_csvToArray($options);

      	$element = $this->formSelect($helperName, $helperValue, $helperAttribs, $helperOptions, $listsep);

      	$element .= $this->_buildJs($name);
		$element .= $this->_hidden($name, $value, array('id' => $name));
		return $element;
	}

	/**
	 * @param string $csv
	 * @return array
	 */
	protected function _csvToArray($csv)
	{
        $arr = array();
      	foreach(WSB_Div::csvToArray($csv, ',') AS $k=>$v) {
      		$arr[$v] = $v;
      	}
      	return $arr;
	}

	/**
	 * @param string $name
	 * @return string
	 */
	private function _buildHelperName($name)
	{
		$name = preg_replace('#[^A-Za-z0-9]#', '_', $name);
		$name = preg_replace('#_$#', '', $name);
		return '__helper_'.$name;
	}

	/**
	 * @param string $name
	 * @return string
	 */
	private function _buildJsOnChange($name)
	{
		$function = $this->_buildJsFunctionName($name);
		return sprintf("%s(this, '%s');", $function, $this->_normalizeId($name));
	}

	/**
	 * @param string $name
	 * @return string
	 */
	private function _buildJsFunctionName($name)
	{
		$name = preg_replace('#[^A-Za-z0-9]#', '_', $name);
		$name = preg_replace('#_$#', '', $name);
		return 'form_select_csv_'.strtolower($name);
	}

	/**
	 * @param string $name
	 * @return string
	 */
	private function _buildJs($name)
	{
      	$js = "
		<script type=\"text/javascript\">
			function " . $this->_buildJsFunctionName($name) . "(select, hiddenId) {
				var element = document.getElementById(hiddenId);
				var elementValue = '';
				var delim = '';
				for (i = 0; i < select.options.length; i++) {
					if (select.options[i].selected == true) {
						elementValue = elementValue + delim + select.options[i].value;
						delim = ',';
					}
				}
				element.value = elementValue;
			}
		</script>
      	";
      	return $js;
	}

}
